package com.tangkun.environment.activity;

import android.os.Bundle;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.Toast;

import com.tangkun.environment.R;
import com.tangkun.environment.application.Session;
import com.tangkun.environment.entity.token.LoginReturn;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.network.NetworkUtil;
import com.tangkun.environment.rx.RxActivity;
import com.tangkun.environment.rx.RxActivityHelper;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.utils.SharePrefercesUtils;
import com.tangkun.environment.utils.StatusBarUtil;
import com.tangkun.environment.view.LoadDialog;
import com.umeng.analytics.MobclickAgent;

import org.simple.eventbus.EventBus;

import retrofit.Retrofit;

/**
 * BaseActivity[v 1.0.0]
 * classes:com.yixin.oaoinventory.base.BaseActivity
 *
 * @author zhoujinjie
 * @date 2016/3/11
 * @time 18:21
 * @description
 */
public class BaseActivity extends RxActivity {

    private LoadDialog loadDialog;
    protected Retrofit retrofit;
    protected NetworkUtil.FromNetwork fromNetwork;
    /**
     * 默认每页的数量
     */
    protected int pageSize = 20;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadDialog = new LoadDialog(this);
        retrofit = NetworkUtil.getRetrofit();
        fromNetwork = retrofit.create(NetworkUtil.FromNetwork.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        setStatusTranslucent();
    }

    /**
     * 隐藏软键盘
     */
    public void hideKeyBoard() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.
                SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

    /**
     * 返回
     */
    public void back() {
        finish();
    }


    private Toast mToast;

    /**
     * showToast
     *
     * @param msg
     */
    public void showToast(String msg) {
        if (mToast == null) {
            mToast = Toast.makeText(BaseActivity.this, msg, Toast.LENGTH_SHORT);
            mToast.setGravity(Gravity.CENTER, 0, 0);//居中显示
        } else {
            mToast.setText(msg);
            mToast.setGravity(Gravity.CENTER, 0, 0);//居中显示
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

    public void cancelToast() {
        if (mToast != null) {
            mToast.cancel();
        }
    }

    /**
     * 返回键监听(不需要的界面重写该方法)
     */
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            finish();
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    /**
     * 返回键监听(不需要的界面重写该方法)
     */
    @Override
    public void onBackPressed() {
        cancelToast();
        finish();
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelToast();
        hideKeyBoard();
    }


    /**
     * 设置状态栏透明
     */
    public void setStatusTranslucent() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            Window window = getWindow();
//            // Translucent status bar
//            window.setFlags(
//                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
//                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        }

        StatusBarUtil.setColor(this, getResources().getColor(R.color.common_toolbar));
    }

    /**
     * 显示加载对话框
     *
     * @param text     提示文本
     * @param listener
     */
    public void showLoading(String text, LoadDialog.OnDialongKeyDownListener listener) {
        showLoading(text, true, listener);
    }

    /**
     * 显示加载对话框
     *
     * @param text              提示文本
     * @param isReturnKeyCancel 返回键是否可取消
     */
    public void showLoading(String text, boolean isReturnKeyCancel) {
        showLoading(text, isReturnKeyCancel, null);
    }

    /**
     * 显示加载对话框
     *
     * @param text 提示文本
     */
    public void showLoading(String text) {
        showLoading(text, true, null);
    }

    /**
     * 显示加载对话框
     */
    public void showLoading() {
        showLoading(null, true, null);
    }

    /**
     * 显示加载对话框
     *
     * @param text              提示文本
     * @param isReturnKeyCancel 返回键是否可取消
     * @param listener          回调返回键事件
     */
    public void showLoading(String text, boolean isReturnKeyCancel, LoadDialog.OnDialongKeyDownListener listener) {
        if (loadDialog == null) {
            loadDialog = new LoadDialog(this);
        }
        loadDialog.show(text, isReturnKeyCancel, listener);
    }


    /**
     * 取消加载对话框
     */
    public void dismissLoading() {
        if (loadDialog != null) {
            loadDialog.dismiss();
        }
    }

    /**
     * 登录接口
     *
     * @param mContext 上下文
     */
    public void login(final BaseActivity mContext) {
        //调用登录接口，成功后跳转主页面MainActivity
        final String userName = SharePrefercesUtils.getUserName(mContext);//用户名
        final String password = SharePrefercesUtils.getPassword(mContext);//密码
        fromNetwork.login(userName, password).compose(new RxActivityHelper<LoginReturn>().ioMain(mContext, false))
                .subscribe(new MySubscribe<LoginReturn>(mContext, false) {

                    @Override
                    protected void success(LoginReturn resultBean) {
                        if (resultBean.data != null) {
                            //本地文件存储用户已登录
                            SharePrefercesUtils.setLoginStatus(mContext, true);
                            LogUtils.e("authmark:" + resultBean.data.authmark);
                            //刷新本地token
                            SharePrefercesUtils.setToken(mContext, resultBean.data.authmark);
                            //保存用户名
                            SharePrefercesUtils.setUserName(mContext, userName);
                            //保存密码
                            SharePrefercesUtils.setPassword(mContext, password);
                            //更新用户信息
                            Session.getInstance().setUserInfo(resultBean.data);
                            //是否绑定
                            if (resultBean.data.bindlist == null || resultBean.data.bindlist.size() == 0) {
                                SharePrefercesUtils.setBindStatus(mContext, false);
                            } else {
                                SharePrefercesUtils.setBindStatus(mContext, true);
                            }
                            //每次调用登录接口后刷新首页和工作页面
                            EventBus.getDefault().post(true, "MainActivity.refreshFragment");//刷新首页和新闻
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }
}
